package com.hljx.config;

import cn.hutool.core.io.IoUtil;
import jakarta.servlet.ReadListener;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequestWrapper;
import org.springframework.util.StreamUtils;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * @BelongsProject: hljx
 * @BelongsPackage: com.hljx.config
 * @Author: lp
 * @CreateTime: 2023-12-21  09:45
 * @Description: TODO
 * @Version: 1.0
 */
public class MyRequestWrapper extends HttpServletRequestWrapper {
    private  byte[] body;
//    private String bodyStr;

    public MyRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        if (body==null) {
            ByteArrayOutputStream bais = new ByteArrayOutputStream();
            IoUtil.copy(request.getInputStream(), bais);
            body = bais.toByteArray();
//        bodyStr= StreamUtils.copyToString(request.getInputStream(), StandardCharsets.UTF_8);
        }
    }

    public String getBody() {
        return new String(body,StandardCharsets.UTF_8);
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        final ByteArrayInputStream bais = new ByteArrayInputStream(body);

        return new ServletInputStream() {

            @Override
            public int read() throws IOException {
                return bais.read();
            }

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }
        };
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(this.getInputStream()));
    }
}
